package com.lzy.business.task;

import com.lzy.business.facade.CouponProfitRecordFacade;
import com.lzy.framework.core.utils.RandomStringUtils;
import com.lzy.framework.tools.date.DateStyle;
import com.lzy.framework.tools.date.DateUtils;
import com.lzy.framework.tools.kv.KvClient;
import com.lzy.product.apis.CouponProfitRecordServiceApi;
import com.lzy.product.apis.OrderYieldRatioServiceApi;
import com.lzy.product.constants.BusinessType.CouponProfitStatus;
import com.lzy.product.dtos.CouponProfitRecordDto;
import com.lzy.product.dtos.OrderYieldRatioDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 卡券宝定时任务
 * Created by WIN7 on 2017/12/29.
 */
@Component
public class CouponsJob {
    public static final Logger LOGGER = LoggerFactory.getLogger(CouponsJob.class);
    //新增收益记录
    public static final String JOB_PRODUCT_PROFIT_RECORD = "job:product:profit:record";
    //更新卡券宝详情
    public static final String JOB_PRODUCT_MEMBER_COUPONS = "job:product:member:coupons";
    //发送推广补贴短信
    public static final String JOB_PRODUCT_PROMOTE_SUBSIDY = "job:product:promote:subsidy";

    @Autowired
    private OrderYieldRatioServiceApi orderYieldRatioServiceApi;
    @Autowired
    private CouponProfitRecordServiceApi couponProfitRecordServiceApi;
    @Autowired
    private CouponProfitRecordFacade couponProfitRecordFacade;
    @Autowired
    private KvClient kvClient;


    //通知声音
    private final static String SOUND = "unbelievable";
    //包名
    private final static String ACTIVITY = "com.lzhy.moneyhll.activity.me.myWallet.MyWalletActivity";

    @Scheduled(cron = "0 0 0 * * ?")   //每天0点执行一次
    public void addProfitRecords() {
        try {
            Thread.sleep(Long.valueOf(RandomStringUtils.random(3, false, true)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHH"));

        // 获取分布式锁
        kvClient.setNx(JOB_PRODUCT_PROFIT_RECORD + now, "");
        try {
            //更新返现开始的订单收益比率记录
            orderYieldRatioServiceApi.updateStartStatus(DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD));
            //更新返现结束的订单收益比率记录
            orderYieldRatioServiceApi.updateBackedStatus(DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD));
            //扫描可计算收益的订单收益比率记录
            List<OrderYieldRatioDto> list = orderYieldRatioServiceApi.queryAvailList(DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD));

            //整合卡券宝收益记录
            if (list != null && list.size() > 0) {
                List<CouponProfitRecordDto> recordDtoList = new ArrayList<>();
                for (OrderYieldRatioDto dto : list) {
                    CouponProfitRecordDto recordDto = new CouponProfitRecordDto();
                    recordDto.setOrderId(dto.getOrderId());
                    recordDto.setMemberId(dto.getMemberId());
                    recordDto.setAmount(dto.getDailyIncome());
                    if (recordDto.getAmount() != null && recordDto.getAmount().compareTo(new BigDecimal(0)) > 0) {
                        //新增卡券宝收益记录
                        recordDto.setId(couponProfitRecordServiceApi.insert(recordDto));
                        recordDtoList.add(recordDto);
                    }
                }

                if (recordDtoList != null && recordDtoList.size() > 0) {
                    //更新卡券宝收益记录状态（1-可限制）
                    couponProfitRecordFacade.updateProfitRecordsStatus(recordDtoList, CouponProfitStatus.LIMITED.getCode());
                }
            }

        } catch (Exception e) {
            //新增卡券宝收益记录失败
            LOGGER.error(now + "新增卡券宝收益记录失败！");
        }
    }

    //可提现余额
    @Scheduled(cron = "0 0 1 * * ?")   //每天1点执行一次
    public void updateCoupons() {
        try {
            Thread.sleep(Long.valueOf(RandomStringUtils.random(3, false, true)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHss"));
        // 获取分布式锁
        kvClient.setNx(JOB_PRODUCT_MEMBER_COUPONS+"1" + now, "");

        try {
            LOGGER.error("1点可提现余额方法执行");
            //扫描可提现收益的卡券宝收益记录
            List<CouponProfitRecordDto> list = couponProfitRecordServiceApi.queryLimitedList();
            if (list != null && list.size() > 0) {
                //更新卡券宝收益记录状态（3-可提现）
                couponProfitRecordFacade.updateProfitRecordsStatus(list, CouponProfitStatus.AVAILED.getCode());
            }
        } catch (Exception e) {
            LOGGER.error(now + "根据卡券宝收益记录增加可提现金额失败！");
        }
    }

    //可提现余额
    @Scheduled(cron = "0 10 1 * * ?")   //每天1点10分执行一次
    public void updateCouponProfit() {
        try {
            Thread.sleep(Long.valueOf(RandomStringUtils.random(3, false, true)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHss"));
        // 获取分布式锁
        kvClient.setNx(JOB_PRODUCT_MEMBER_COUPONS+"1" + now, "");

        try {
            LOGGER.error("1点10分可提现余额方法执行");
            //扫描可提现收益的卡券宝收益记录
            List<CouponProfitRecordDto> list = couponProfitRecordServiceApi.queryLimitedList();
            if (list != null && list.size() > 0) {
                //更新卡券宝收益记录状态（3-可提现）
                couponProfitRecordFacade.updateProfitRecordsStatus(list, CouponProfitStatus.AVAILED.getCode());
            }
        } catch (Exception e) {
            LOGGER.error(now + "根据卡券宝收益记录增加可提现金额失败！");
        }
    }

    //佣金
    @Scheduled(cron = "0 20 1 * * ?")   //每天1点20分执行一次
    public void updateCouponsProfit() {
        try {
            Thread.sleep(Long.valueOf(RandomStringUtils.random(3, false, true)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHss"));

        // 获取分布式锁
        kvClient.setNx(JOB_PRODUCT_MEMBER_COUPONS+"2" + now, "");

        try {
            LOGGER.error("1点20分佣金方法执行");
            //扫描可提现收益的卡券宝收益记录
            List<CouponProfitRecordDto> list = couponProfitRecordServiceApi.queryLimitedListByCommision();
            if (list != null && list.size() > 0) {
                //更新卡券宝收益记录状态（3-可提现）
                couponProfitRecordFacade.updateProfitRecordsStatus(list, CouponProfitStatus.AVAILED.getCode());
            }
        } catch (Exception e) {
            LOGGER.error(now + "更新卡券宝收益记录佣金失败！");
        }
    }

    //佣金
    @Scheduled(cron = "0 30 1 * * ?")   //每天1点30分执行一次
    public void updateCouponsProfits() {
        try {
            Thread.sleep(Long.valueOf(RandomStringUtils.random(3, false, true)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHss"));

        // 获取分布式锁
        kvClient.setNx(JOB_PRODUCT_MEMBER_COUPONS+"2" + now, "");

        try {
            LOGGER.error("1点30分佣金方法执行");
            //扫描可提现收益的卡券宝收益记录
            List<CouponProfitRecordDto> list = couponProfitRecordServiceApi.queryLimitedListByCommision();
            if (list != null && list.size() > 0) {
                //更新卡券宝收益记录状态（3-可提现）
                couponProfitRecordFacade.updateProfitRecordsStatus(list, CouponProfitStatus.AVAILED.getCode());
            }
        } catch (Exception e) {
            LOGGER.error(now + "更新卡券宝收益记录佣金失败！");
        }
    }

    /**
     * 每天10点发送推送短信
     */
    @Scheduled(cron = "0 0 10 * * ?")   //每天10点执行一次
    public void sendPromote() {
        LocalDate now = LocalDate.now();
        try {
            Thread.sleep(Long.valueOf(RandomStringUtils.random(3, false, true)));
            // 获取分布式锁
            kvClient.setNx(JOB_PRODUCT_PROMOTE_SUBSIDY + now, "");
        } catch (InterruptedException e) {
            LOGGER.error("定时任务：每天10点发送推送短信======获取分布式锁失败！");
        }
        Integer m = couponProfitRecordFacade.sendPromote();
        LOGGER.debug("========= 任务调度器正在执行 [ sendPromote ]，共有 " + m + " 条推广补贴推送消息成功推送...");
    }

}

